<?php

namespace App\Models\Common;

use App\Traits\UuidTrait;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;

/**
 * App\Models\Common\BaseModel
 *
 * @method static Builder|BaseModel newModelQuery()
 * @method static Builder|BaseModel newQuery()
 * @method static Builder|BaseModel query()
 * @mixin \Eloquent
 */
class BaseModel extends Model
{
    use UuidTrait;

//    /**
//     * 为数组 / JSON序列化准备一个日期
//     *
//     * @param  DateTimeInterface  $date
//     * @return string
//     */
//    protected function serializeDate(DateTimeInterface $date): string
//    {
//        return $date->format('Y-m-d H:i:s');
//    }

    /**
     * @param Builder $query
     * @param int $page
     * @param int $perPage
     * @param string $load
     * @param array $hidden
     * @return array
     */
    public static function getList(Builder $query, int $page = 1, int $perPage = 10, string $load = '', array $hidden = [], $sort = '-id'): array
    {
        $skip = ($page - 1) * $perPage;
        $total = $query->count();

        $totalPage = 0 === $total ? 0 : ceil($total / $perPage);

        $query->skip($skip)->take($perPage);

        if ($sort) {
            if (\Str::startsWith($sort, '-')) {
                $query->orderByDesc(substr($sort, 1));
            } else {
                $query->orderBy($sort);
            }
        }

        if ('' === $load) {
            $list = $query->get()->makeHidden($hidden);
        } else {
            $list = $query->get()->load($load)->makeHidden($hidden);
        }

        return [
            'total' => $total,
            'current_page' => $page,
            'per_page' => $perPage,
            'pages' => $totalPage,
            'list' => $list,
        ];
    }
}
